<#assign ctx=request.contextPath />
<#import '${ctx}/sys/include/table/select.html' as select />
<#macro atom aggs="false" url="${ctx}/biz/chart/draw">
<div name="metric_cards">
	<div class="layui-card metric_card" name="metric_card">
		<div class="layui-card-header">分析指标</div>
    	<div class="layui-card-body">
    		<div name="metric_detail" class="layui-collapse metric_box">
    			<div class="layui-colla-item">
    				<div class="layui-colla-title">
    					指标定义<i class="layui-icon layui-colla-icon"></i>
    				</div>
    				<div class="layui-colla-content layui-show">
    					<div class="layui-form-item">
			    			<label class="layui-form-label">指标</label>
			    			<div class="layui-input-block">
						        <select name="aggregation" lay-verify="required"
						                lay-filter="metrics_select">
						            <option value="count">计数</option>
						            <option value="sum">累加</option>
						            <option value="avg">平均值</option>
						            <option value="terms">词拆分</option>
						            <option value="date">时间拆分</option>
						        </select> <input name="metric_type" type="hidden" value="count"/>
			   				</div>
						</div>
						<div class="layui-form-item layui-hide">
			    			<label class="layui-form-label">字段</label>
			    			<div class="layui-input-block"><@select.table
						        name="metrics" show="metricsName" title="alias"
						        url="${ctx}/biz/c/p/field-select-table" />
						    </div>
						</div>
						<div class="layui-form-item">
			                <label class="layui-form-label">拆分个数</label>
			                <div class="layui-input-block">
			                	<input name="metric_size" type="text" class="layui-input" value="10"/>
			                </div>
			            </div>
						<div name="sub_btn" class="layui-hide" style="float: left">
							<a name="sub_metric" class="layui-btn layui-btn-primary layui-btn-sm" style="margin-bottom: 15px;">
						        	添加子指标
						    </a>
						</div>
						<div class="layui-clear"></div>
    				</div>
    			</div>
    		</div>
			<div name="btn_group" class="" style="float:right;margin-top:5px;">
			    <a name="add_metric" class="layui-btn layui-btn-primary layui-btn-sm">
			        <i class="layui-icon">&#xe654;</i>
			    </a>
			    <a name="del_metric" class="layui-btn layui-btn-primary layui-btn-sm">
			        <i class="layui-icon">&#xe640;</i>
			    </a>
			</div>
			<div class="layui-clear"></div>
		</div>
	</div>
</div>
<#if aggs=='true'>
<div name="aggregation_cards">
    <div class="layui-card" name="aggregation_card">
        <div class="layui-card-header">拆分维度</div>
        <div class="layui-card-body">
        	<div name="aggregation_detail" class="layui-collapse metric_box">
        		<div class="layui-colla-item">
        		<div class="layui-colla-title">
    					坐标轴定义<i class="layui-icon layui-colla-icon"></i>
    			</div>
    			<div class="layui-colla-content layui-show">
		            <div class="layui-form-item">
		                <label class="layui-form-label">拆分方式</label>
		                <div class="layui-input-block">
		                    <select name="aggregation" lay-verify="required"
		                            lay-filter="aggs_select">
		                        <option value="terms">按字段值</option>
		                        <option value="date">按时间</option>
		                        <option value="range">按区间</option>
		                        <option value="filter">按条件</option>
		                    </select> <input name="aggregation_type" type="hidden" value="terms"/>
		                </div>
		            </div>
		            <div id="field_selector" class="layui-form-item">
		                <label class="layui-form-label">聚合字段</label>
		                <div class="layui-input-block"><@select.table name="aggs"
		                    title="alias" show="aggsName"
		                    url="${ctx}/biz/c/p/field-select-table" />
		                </div>
		            </div>
		            <div id="time_interval" class="layui-form-item layui-hide">
		                <label class="layui-form-label">时间区间</label>
		                <div class="layui-input-block">
		                    <select name="time_interval" lay-verify="required"
		                            lay-filter="interval_select">
		                        <option value="1m">按分钟</option>
		                        <option value="1h">按小时</option>
		                        <option value="1d">按天</option>
		                        <option value="1M" selected>按月</option>
		                        <option value="1y">按年</option>
		                    </select> <input name="time_interval" type="hidden" value="1M"/>
		                </div>
		            </div>
		            <div class="layui-form-item">
		                <label class="layui-form-label">拆分个数</label>
		                <div class="layui-input-block">
		                	<input name="metric_size" type="text" class="layui-input" value="10"/>
		                </div>
		            </div>
            	</div>
            	</div>
            </div>
            <div class="layui-clear"></div>
        </div>
    </div>
</div>
</#if>
<script type="text/javascript">
var metricArray=[];
var dimensionArray=[];
var chart;
layui.use(['jquery','form','element','appJs'],function(){
	var $ = layui.$
	,form = layui.form
	,element = layui.element
	,app = layui.appJs;

    element.on('tab(graph_config)', function (data) {
        if (data.index == 0) {
        	drawPic();
        }
    });

    window.drawPic = function drawPic(query) {
    	if(chart) {
       		chart.clear();
       	}
	   metricArray.length=0;
	   dimensionArray.length=0;
       var metricDef = metricRequest();
       var dimensionDef = dimensionRequest();
       fillMeta(metricDef);
       var req = {};
       req.metric = metricDef;
       req.dimension = dimensionDef;
       req.dsId = $('input[name="dsId"]').val();
	   req.query = {};
	   if(query){
		   req.query = query();
	   }
       app.ajax('post','${url}',{req:JSON.stringify(req)},function(data){
    	   if(data.code == 0) {
        	  // var option = handleResponse(req,dimensionArray,metricArray,data.values.data);
        	   if(chart) {
	   	       		chart.destroy();
	   	       	}
        	   chart = new G2.Chart({
	           	    container: 'pic',
	           	 	autoFit: true,
	           	    height: window.innerHeight - 250
	           	});
        	   try{
        		   handleResponse(chart,data.values.data);
	        	   //app.pic(chart,option);
	        	   chart.render();
        	   }catch(e){
        		   console.log(e)
        		   layer.msg('解析出错');
        	   }
    	   }else {
    		   layer.msg(data.code+': '+data.msg);
    	   }
       });
    }
    form.on('select(metrics_select)', function (data) {
        var ele = data.elem;
        var val = data.value;
        $(ele).parent().find('input[name="metric_type"]').val(val);
        if (val != 'count') {
            $(ele).parent().parent().next().removeClass('layui-hide');
        } else {
            $(ele).parent().parent().next().addClass('layui-hide');
        }
        if(val == 'terms') {
        	$(ele).parent().parent().parent().find('[name="sub_btn"]').removeClass('layui-hide');
        }else {
        	$(ele).parent().parent().parent().find('[name="sub_btn"]').addClass('layui-hide');
        }
        setHeight();
    });
	form.on('select(aggs_select)',function(data){
		 var ele = data.elem;
	     var val = data.value;
	     if (val == 'date') {
			$("#time_interval").removeClass("layui-hide");
	     }else {
	    	 $("#time_interval").addClass("layui-hide");
	     }
	     $("input[name='aggregation_type']").val(val);
	});
	
	form.on('select(interval_select)',function(data){
		 var ele = data.elem;
	     var val = data.value;
	     $("input[name='time_interval']").val(val);
	});

	function bindMetricButton() {
	    $('[name="metric_cards"]').find('[name="btn_group"]:first').find('a[name="del_metric"]').hide();
	    $('[name="metric_cards"]').find('a[name="add_metric"]').unbind('click');
	    $('[name="metric_cards"]').find('a[name="add_metric"]').bind('click', function () {
	    	var container = $('div[name="metric_cards"]');
	        //var lastCard = $(this).parent().parent().parent();
	        //var newCard = lastCard.clone(true);
	        var newCard = $metric.clone(true);
	      	newCard.find('input[name="metricsName"]').val("");
	        newCard.find('input[name="metrics"]').val("");
	        newCard.find('input[name="metricsName"]').parent().parent().parent().addClass('layui-hide');
	        container.append(newCard);
	        //lastCard.after(newCard);
	        $('[name="metric_cards"]').find('[name="btn_group"]').find('a[name="add_metric"]').hide();
	        $('[name="metric_cards"]').find('[name="btn_group"]:last').find('a[name="add_metric"]').show();
	        $('[name="metric_cards"]').find('[name="btn_group"]').find('a[name="del_metric"]').show();
	        $('[name="metric_cards"]').find('[name="btn_group"]:first').find('a[name="del_metric"]').hide();
	        form.render();
	        setHeight();
	    });
	    $('a[name="del_metric"]').bind('click', function () {
	        $(this).parent().parent().parent().remove();
	        $('[name="metric_cards"]').find('[name="btn_group"]:last').find('a[name="add_metric"]').show();
	    });
	}
	function bindSubMetricButton() {
		 $('[name="metric_cards"]').find('a[name="sub_metric"]').unbind('click');
		 $('[name="metric_cards"]').find('a[name="sub_metric"]').bind('click',function(){
			var $cloneItem = $subMetric.clone(true);
			$(this).parent().parent().append($cloneItem);
			bindSubMetricButton();
			form.render();
			setHeight();
		 });
		 $('[name="metric_cards"]').find('a[name="del_sub_metric"]').unbind('click');
		 $('[name="metric_cards"]').find('a[name="del_sub_metric"]').bind('click',function(){
			 $(this).parent().parent().parent().remove();
		 });
	}
	bindMetricButton();
	bindSubMetricButton();

	function setHeight() {
		parent.resize();
	}

	function dimensionRequest() {
		var dimension = {};
		var $metricCards = $('div[name="aggregation_cards"]').children('[name="aggregation_card"]');
		dimension.type = $metricCards.find('input[name="aggregation_type"]:first').val();
		dimension.field = $metricCards.find('input[name="aggs"]:first').val();
		dimension.size = $metricCards.find('input[name="aggs_size"]:first').val();
		dimension.interval = $metricCards.find('input[name="time_interval"]:first').val();
		return dimension;
	}

	function metricRequest() {
		var metrics = [];
		var $metricCards = $('div[name="metric_cards"]').children('[name="metric_card"]');
		$metricCards.each(function(id, card){
			var metricObj = {};
			var $item = $(card).find('[name="metric_detail"]:first');
			var metric_type = $item.find('input[name="metric_type"]:first').val();
            var metric_field = $item.find('input[name="metrics"]:first').val();
            var metric_size = $item.find('input[name="metric_size"]:first').val();
            var interval = $item.find("input[name='time_interval']").val();
            if(metric_type != 'count') {
	            metricObj.field=metric_field;
	            metricObj.type=metric_type;
	            metricObj.size = metric_size;
	            metricObj.interval=interval;
	            var $sub = $item.find('.layui-colla-content:first').children('[name="metric_detail"]');
	            if($sub.length >0) {
		            metricObj.metric = [];
		            _fill(metricObj.metric,$sub);
	            }
	            metrics.push(metricObj);
	            //fillMeta(metricObj);
            }
		});
		return metrics;
	}

	function _fill(arr,$items) {
		$items.each(function(id,item){
			var metricObj = {};
			var metric_type = $(item).find('input[name="metric_type"]:first').val();
            var metric_field = $(item).find('input[name="metrics"]:first').val();
            var metric_size = $(item).find('input[name="metric_size"]:first').val();
            var interval = $(item).find("input[name='time_interval']").val();
            if(metric_type != 'count') {
	            metricObj.field=metric_field;
	            metricObj.type=metric_type;
	            metricObj.size = metric_size;
	            metricObj.interval = interval;
	            var $sub = $(item).find('[name="metric_detail"]');
	            if($sub.length>0) {
		            metricObj.metric = [];
		            _fill(metricObj.metric,$(item).find('.layui-colla-content:first').children('[name="metric_detail"]'));
	            }
	            arr.push(metricObj);
	            //fillMeta(metricObj);
            }
		});
	}

	function fillMeta(metrics) {
		for(var metric of metrics) {
			var metricPack = {};
			_fillMeta(metricPack,metric);
			metricArray.push(metricPack);
		}

	}

	function _fillMeta(metricPack,metricObj) {
		if(!metricObj) return;
		if(metricObj.field) {
			app.async_ajax('get', '${ctx}/biz/data/ds/field/get', {id: metricObj.field}, function (d) {
                if (d.code == 0) {
					metricPack.meta = d.values.data;
					metricPack.field = metricObj.field;
					metricPack.type = metricObj.type;
                }else {
                	layer.msg(d.code+': '+d.msg);
                }
            });
			if(metricObj.metric) {
				metricPack.metric = [];
				for(var sub of metricObj.metric) {
					var subPack = {};
					_fillMeta(subPack,sub);
					metricPack.metric.push(subPack);
				}
			}
		}
	}

	var $metric = $('div[name="metric_card"]').clone(true);
	var $subMetric = $('div[name="metric_detail"]').clone(true);
	$subMetric.find('.layui-colla-title').append('<a name="del_sub_metric" class="layui-btn layui-btn-primary layui-btn-sm" style="position:absolute;right:5px;margin-top:5px;"><i class="layui-icon">&#xe640;</i></a>');
	form.render();
});

</script>
</#macro>